package com.bjy.qa.util.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.bjy.qa.entity.user.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Component
public class JWTUtils {
    static String secretKey;

    @Value("${qa-platform.secret-key}")
    public void setSecretKey(String secretKey) {
        JWTUtils.secretKey = secretKey;
    }

    /**
     * 获取token
     * @param user user
     * @return token
     */
    public static String getToken(User user) {
        return generateToken(user, null, 7); // 默认令牌过期时间7天
    }

    /**
     * 生成token
     * @param user user信息
     * @param extMap 扩展信息
     * @param day 有效期天数
     * @return
     */
    public static String generateToken(User user, Map<String, Object> extMap, int day) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, day);

        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("id", user.getId())
                .withClaim("account", user.getAccount());

        // 添加扩展参数
        if (extMap != null) {
            for (Map.Entry<String, Object> entry : extMap.entrySet()) {
                switch (entry.getValue().getClass().getSimpleName()) {
                    case "Long":
                        builder.withClaim(entry.getKey(), (Long) entry.getValue());
                        break;
                    case "Boolean":
                        builder.withClaim(entry.getKey(), (Boolean) entry.getValue());
                        break;
                    case "String":
                        builder.withClaim(entry.getKey(), (String) entry.getValue());
                        break;
                    case "Integer":
                        builder.withClaim(entry.getKey(), (Integer) entry.getValue());
                        break;
                    case "Double":
                        builder.withClaim(entry.getKey(), (Double) entry.getValue());
                        break;
                    case "Date":
                        builder.withClaim(entry.getKey(), (Date) entry.getValue());
                        break;
                }
            }
        }

        return builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(user.getCode()));
    }
}
